package com.wisdytech.linkdcs.configuration.service.impl;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.enums.FactoryModelType;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.linkdcs.configuration.dao.ITtEqConfigurationDao;
import com.wisdytech.linkdcs.configuration.dto.ConfigurationEqDto;
import com.wisdytech.linkdcs.configuration.dto.ConfigurationParamDto;
import com.wisdytech.linkdcs.configuration.model.TtEqConfiguration;
import com.wisdytech.linkdcs.configuration.service.ITtEqConfigurationService;
import com.wisdytech.linkdcs.factory.model.Factory;
import com.wisdytech.linkdcs.factory.model.ProductionLine;
import com.wisdytech.linkdcs.factory.model.Shop;
import com.wisdytech.linkdcs.factory.service.TmFactoryService;
import com.wisdytech.linkdcs.factory.service.TmProductionLineService;
import com.wisdytech.linkdcs.factory.service.TmShopService;
import com.wisdytech.linkdcs.system.model.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dlb
 * @since 2018-05-07
 */
@Service
@Transactional
public class TtEqConfigurationServiceImpl  extends BaseService<ITtEqConfigurationDao, TtEqConfiguration> implements ITtEqConfigurationService {

	/**
	 * logger
	 */
	private static final Logger logger = LoggerFactory.getLogger(TtEqConfigurationServiceImpl.class);
	
	@Resource
	private ITtEqConfigurationDao ttEqConfigurationDao;

	/**
	 * 厂区服务类
	 */
	@Resource
	private TmFactoryService tmFactoryService;

	@Resource
	private TmProductionLineService tmProductionLineService;

	@Resource
	private TmShopService tmShopService;


	@Override
	public PageInfo<Map<String, Object>> listConfigurationByFilter(String type,String code, String factoryId, String locationId, Filter filter,String configurationType) {
		Map<String, Object> params = new HashMap<>();
		if(StringUtils.isBlank(type)) {
			return null;
		}
		params.put("type",type);
		if(StringUtils.isNotBlank(code)) {
			params.put("code",code);
		}
		if(StringUtils.isNotBlank(locationId)) {
			params.put("locationId",locationId);
		}
		//组装厂区查询条件
		List<String> ids = new ArrayList<>();
		if(StringUtils.isNotBlank(factoryId)) {
			if(FactoryModelType.SHOP.getCode().equals(type)) {
				List<Shop> shopList = this.tmShopService.listAllShops(factoryId);
				//如果查询的厂区下没有产线，则不可能有车间组态信息，直接返回null
				if(shopList == null || shopList.size() == 0) return new PageInfo<>(new ArrayList<Map<String, Object>>());
				for (Shop shop:
						shopList) {
					ids.add(shop.getPkId());
				}
			}
			if(FactoryModelType.LINE.getCode().equals(type)) {
				List<ProductionLine> lineList = this.tmProductionLineService.listAllLine(factoryId);
				//如果查询的厂区下没有产线，则不可能有产线组态信息，直接返回null
				if(lineList == null || lineList.size() == 0) return new PageInfo<>(new ArrayList<Map<String, Object>>());
				for (ProductionLine line:
						lineList) {
					ids.add(line.getPkId());
				}
			}
		}
		params.put("ids",ids);
		params.put("configurationType",configurationType);
		//设定分页数据
		PageHelper.startPage(filter.getNum(), filter.getSize());
		List<Map<String, Object>> list = ttEqConfigurationDao.listConfigurationByFilter(params);
		for (Map<String, Object> map: list) {
			mergeConfigurationInfo(map);
		}
		PageInfo<Map<String, Object>> page = new PageInfo<>(list);
		return page;
	}

    @Override
    public void saveOrUpdateConfiguration(TtEqConfiguration ttEqConfiguration, SysUser user) {
        //校验操作人
        if(user == null) {
            logger.info("user is null");
            throw new ServiceException("操作人不能为空");
        }
        if(ttEqConfiguration!=null) {
            //检验组态编号
            if(!StringUtils.isNotBlank(ttEqConfiguration.getCode())) {
                throw new ServiceException("组态编码不能为空");
            }
            //校验文档编号是否重复
            EntityWrapper<TtEqConfiguration> ew =new EntityWrapper<>();
            ew.eq("code",ttEqConfiguration.getCode());
            ew.eq("del_flag", CommonConstants.DEL_FLAG);
            //修改
            if(StringUtils.isNotBlank(ttEqConfiguration.getPkId())) {
                ew.ne("pk_id",ttEqConfiguration.getPkId());
                Integer count = ttEqConfigurationDao.selectCount(ew);
                if(count>0) {
                    throw new ServiceException("组态编码重复");
                }
                ttEqConfiguration.setUpdateDate(new Date());
                ttEqConfiguration.setUpdateUser(user.getUsername());
                ttEqConfigurationDao.updateById(ttEqConfiguration);
            } else {
            //保存
                if(ttEqConfiguration.getConfigurationType().equals("2")){
                    EntityWrapper<TtEqConfiguration> ew1 =new EntityWrapper<>();
                    ew1.eq("LOCATION_ID",ttEqConfiguration.getLocationId());
                    ew1.eq("CONFIGURATION_TYPE",ttEqConfiguration.getConfigurationType());
                    ew1.eq("del_flag", CommonConstants.DEL_FLAG);
                    Integer count1 = ttEqConfigurationDao.selectCount(ew1);
                    if(count1>0) {
                        if(ttEqConfiguration.getType().equals("1")){
                            throw new ServiceException("同一个厂区只能建立一个组态");
                        }
                        if(ttEqConfiguration.getType().equals("2")){
                            throw new ServiceException("同一个产线只能建立一个组态");
                        }
                        if(ttEqConfiguration.getType().equals("3")){
                            throw new ServiceException("同一个车间只能建立一个组态");
                        }


                    }
                }
                Integer count = ttEqConfigurationDao.selectCount(ew);
                if(count>0) {
                    throw new ServiceException("组态编码重复");
                }
                ttEqConfiguration.setDelFlag(CommonConstants.DEL_FLAG);
                ttEqConfiguration.setCreateDate(new Date());
                ttEqConfiguration.setCreateUser(user.getUsername());
                ttEqConfigurationDao.insert(ttEqConfiguration);
            }
        }
    }

    @Override
    public Map<String, Object> getConfigurationById(String pkId) {
        Map<String, Object> configuration;
        if(StringUtils.isNotBlank(pkId)) {
            configuration = ttEqConfigurationDao.getConfigurationById(pkId);
            mergeConfigurationInfo(configuration);
            return configuration;
        }
        return null;
    }

	@Override
	public void deleteConfiguration(String pkIds) {
		String[] deletePkIds = pkIds.split(",");
		if(deletePkIds.length == 0) return;
		List<String> pkIdCollection = Arrays.asList(deletePkIds);
		ttEqConfigurationDao.deleteBatchIds(pkIdCollection);
	}

	/**
	 * 调用接口返回厂区产线车间信息
	 * @param map 传参
	 */
	private void mergeConfigurationInfo(Map<String, Object> map) {
		String type = map.get("type")+"";
		String pkId = map.get("locationId")+"";
		if(StringUtils.isBlank(type)) return;
		if(StringUtils.isBlank(pkId)) return;
		//厂区
		if(FactoryModelType.FACTORY.getCode().equals(type)) {
			Factory factory = tmFactoryService.getFactoryById(pkId);
			if(factory!=null) {
			    map.put("factoryId",pkId);
				map.put("identifier",factory.getIdentifier());
				map.put("factoryCode",factory.getFactoryCode());
				map.put("factoryName",factory.getFactoryName());
			}
		}
		//产线
		if(FactoryModelType.LINE.getCode().equals(type)) {
			ProductionLine productionLine = tmProductionLineService.getProductById(pkId);
			if(productionLine!=null) {
			    map.put("lineId",pkId);
				map.put("lineCode",productionLine.getLineCode());
				map.put("lineName",productionLine.getLineName());
				map.put("factoryName",productionLine.getFactoryName());
				map.put("factoryId",productionLine.getFactoryId());
				map.put("operation",productionLine.getOperationName());
			}

		}
		//车间
		if(FactoryModelType.SHOP.getCode().equals(type)) {
			Shop shop = tmShopService.getShopById(pkId);
			if(shop!=null) {
                map.put("shopId",pkId);
				map.put("shopCode",shop.getShopCode());
				map.put("shopName",shop.getShopName());
				map.put("factoryName",shop.getFactoryName());
				map.put("factoryId",shop.getFactoryId());
				map.put("operation",shop.getOperationName());
			}
		}
	}

	@Override
	public List<ConfigurationEqDto> getConfigurationEqLists(String id) {
		
		TtEqConfiguration ttEqConfiguration =
				ttEqConfigurationDao.selectById(id);
		
		if(null == ttEqConfiguration) {
			return Collections.emptyList();
		}
		
		return getConfigurationEqLists(ttEqConfiguration);
	}

	@Override
	public List<ConfigurationEqDto> getConfigurationEqLists(TtEqConfiguration ttEqConfiguration) {
		
		String jsonFile =ttEqConfiguration.getJsonEquips();
		
		if(StringUtils.isBlank(jsonFile)) {
			return Collections.emptyList();
		}
		
		//解析设备json
		try {
			List<ConfigurationEqDto> lists =
					 JSON.parseArray(jsonFile, ConfigurationEqDto.class);
			return lists;
		} catch (Exception e) {
			logger.error("解析组态设计json失败！！组态记录为"+ttEqConfiguration.getPkId()+"数据格式为"+jsonFile ,e);
			return Collections.emptyList();
		}
//		 
//		
//		//整个组态json
//		JSONObject  object =JSONObject.parseObject(jsonFile);
//		List<ConfigurationEqDto> eqDtos =new ArrayList<>();
//		
//		return parseJson(object,eqDtos);
	}
	
	
	/**
	 * 循环解析保存的组态信息
	 * @param object 组态对象
	 * @param eqDtos
	 * @return
	 */
	@Deprecated
	private List<ConfigurationEqDto> parseJson(JSONObject  object,List<ConfigurationEqDto> eqDtos){

		//设备对象
		JSONArray jsonArray=object.getJSONArray("objects");
		
		//无设备对象跳出
		if(null == jsonArray || jsonArray.size()<=0) {
			return eqDtos;
		}
		
		for(int i=0;i<jsonArray.size();i++) {
			
			
			ConfigurationEqDto eqDto=new ConfigurationEqDto();

			JSONObject eqObject= jsonArray.getJSONObject(i);
			
			//首先判断是否有object 有则进入嵌套循环
			//设备对象
			JSONArray json2Array=eqObject.getJSONArray("objects");
			//无设备对象跳出
			if(null != json2Array && json2Array.size()>0) {
				//嵌套循环
				parseJson(eqObject, eqDtos);
			}
			
			
			//绑定的设备对象
			JSONObject eqBindObject =
					eqObject.getJSONObject("dataBindingProperty");
			if(null ==eqBindObject) {
				continue;
			}
			String equipmentId =eqBindObject.getString("equipNo");
			if(StringUtils.isBlank(equipmentId)) {
				continue;
			}
			//设备id
			eqDto.setEquipNo(equipmentId);
			
			//参数对象
			JSONArray paramArray=
					eqBindObject.getJSONArray("dataSettingProperty");
			
			
			List<ConfigurationParamDto> properties=new ArrayList<>();
			
			if(null == paramArray || paramArray.size()==0) {
				continue;
			}
			
			for(int j=0;j<paramArray.size();j++) {
				
				ConfigurationParamDto paramDto=new ConfigurationParamDto();
				
				JSONObject paramObject= paramArray.getJSONObject(j);
				//解析参数id
				String paramId =paramObject.getString("paramId");
				paramDto.setParamId(paramId);
				//给予默认值
				paramDto.setValue(0.00);
				properties.add(paramDto);
				
			}
			
			eqDto.setProperties(properties);
			eqDtos.add(eqDto);

		}
		
		
		return eqDtos;
	}
	
	/**
	 * 解析保存的组态json
	 * @param jsonFile json文件
	 * @return list
	 */
	@Deprecated
	private List<ConfigurationEqDto> parseJson(String jsonFile){
		
		List<ConfigurationEqDto> eqDtos=new ArrayList<>();
		
		
		//整个组态json
		JSONObject  object =JSONObject.parseObject(jsonFile);
		//设备对象
		JSONArray jsonArray=object.getJSONArray("objects");
		
		for(int i=0;i<jsonArray.size();i++) {
			ConfigurationEqDto eqDto=new ConfigurationEqDto();
			
			
			JSONObject eqObject= jsonArray.getJSONObject(i);
			
			//绑定的设备对象
			JSONObject eqBindObject =
					eqObject.getJSONObject("dataBindingProperty");
			if(null ==eqBindObject) {
				continue;
			}
			//设备id
			eqDto.setEquipNo(eqBindObject.getString("equipId"));
			
			//参数对象
			JSONArray paramArray=
					eqBindObject.getJSONArray("dataSettingProperty");
			
			
			List<ConfigurationParamDto> properties=new ArrayList<>();
			
			if(null == paramArray || paramArray.size()==0) {
				continue;
			}
			
			for(int j=0;j<paramArray.size();j++) {
				
				ConfigurationParamDto paramDto=new ConfigurationParamDto();
				
				JSONObject paramObject= paramArray.getJSONObject(j);
				//解析参数id
				String paramId =paramObject.getString("paramId");
				paramDto.setParamId(paramId);
				
				properties.add(paramDto);
				
			}
			
			eqDto.setProperties(properties);
			eqDtos.add(eqDto);
			
			
		}
		
		return eqDtos;
		
	}

	@Override
	public boolean saveConfiguration(String id, String json) {
		TtEqConfiguration tc =new TtEqConfiguration();
		tc.setPkId(id);
		tc.setJsonFile(json);
		Integer result =ttEqConfigurationDao.updateById(tc);
		if(null != result || result >0) {
			return true;
		}
		return false;
	}

	@Override
	public TtEqConfiguration getConfigurationObjById(String pkId) {
		
		return ttEqConfigurationDao.selectById(pkId);
	}

	@Override
	public List<TtEqConfiguration> listConfiguration(String locationId,String configurationType) {
		EntityWrapper<TtEqConfiguration> ew = new EntityWrapper<>();
		ew.eq("DEL_FLAG", "0");
		ew.eq("LOCATION_ID", locationId);
		ew.eq("CONFIGURATION_TYPE",configurationType);
		ew.setSqlSelect("PK_ID","NAME");
		
		return ttEqConfigurationDao.selectList(ew);
	}
	
	
	
	

}
